package com.lst.api.config;

import com.lst.api.utils.TokenUtil;
import com.lst.tools.custom.annotation.TokenPermission;
import com.lst.tools.custom.constants.TokenConstants;
import com.lst.tools.custom.exception.TokenErrorException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * aop切面类
 *
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@Aspect
@Configuration
public class VerifyTokenConfig {

    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 定义切点Pointcut
     */
    @Pointcut("execution(* com.lst.api.controller.*.*(..))")
    public void executeController() {
    }

    @Before("executeController()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ticket = request.getHeader(TokenConstants.ACCESS_TOKEN_HEADER);
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        TokenPermission tokenPermission = method.getAnnotation(TokenPermission.class);
        boolean isLegal = tokenUtil.isLegal(ticket, tokenPermission);
        if (!isLegal) {
            throw new TokenErrorException("Token error！");
        }
    }
}
